/*
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *  http://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */
package com.amazonaws.demo;
//test!!!!!
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.amazonaws.demo.sdb.SimpleDB;

public class LogInPage extends Activity {
    
	private static final String success = "Welcome to The AWS Browser Demo!";
	private static final String fail = "Load Failed. Please Try Restarting the Application.";
	

	protected Button logInButton;
	private Button newUserButton;
	private EditText logInName;
	private EditText password;
	private boolean isValidUser;
	private Context context;
	
	public Handler myHandler;
	
	public final int VERIFY_FINISHED = 1;
	public final int VERIFY_FAILED = 2;
	public final int VERIFY_TEST = 3;

	
    public static AmazonClientManager clientManager = null;
    	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // get the layout 
        context = this;
        logInButton = (Button) findViewById(R.id.map_button);
        newUserButton = (Button) findViewById(R.id.newUser);
        clientManager = new AmazonClientManager();
        logInName = (EditText)findViewById(R.id.loginName);
		password = (EditText)findViewById(R.id.password);
        
		//update the lastTimeSendMsg in every 24 hours
		SharedPreferences settings = getSharedPreferences("preference", 0);
		
		if(settings.contains("lastTimeSendMsg")){		
			SharedPreferences.Editor editor = settings.edit();
			if (System.currentTimeMillis() - settings.getLong("lastTimeSendMsg", 0) > 1000 * 3600* 24){ 
				editor.putInt("msgCounter", 0);
				editor.putLong("lastTimeSendMsg", System.currentTimeMillis());
				editor.commit();
			}
		}
		
		// click newUser go to newUser Activity
        newUserButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
    			startActivity(new Intent(LogInPage.this, newUser.class));
			}
		});
        
        // Check if the username and password are correct
     	if ( LogInPage.clientManager.hasCredentials() ){

    		this.wireButtons();
    		
    	} 
        else {
    		this.displayCredentialsIssueAndExit();
    		
    	}       

		myHandler = new Handler(){
			public void handleMessage(Message msg){
				// get the data from other thread
				switch(msg.what){
				case VERIFY_FINISHED:
					Intent i = new Intent(LogInPage.this, map.class);
					i.putExtra("userName", logInName.getText().toString());
					startActivity(i);
					break;
				case VERIFY_FAILED:
		    		Toast.makeText(getApplicationContext(), "Log in failed", Toast.LENGTH_SHORT).show();
					break;
				case VERIFY_TEST:
					i = new Intent(LogInPage.this, map.class);
					i.putExtra("userName", "2060000001");
					startActivity(i);
					break;
				
				}
			}
		};
    }
        
    private void wireButtons(){
		logInButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Thread thread = new Thread(new Runnable(){
					public void run(){
						verifyUser(logInName.getText().toString(), password.getText().toString());
					}
				});
				thread.start();
			}
		});
        
    }
        
    protected void displayCredentialsIssueAndExit() {
        AlertDialog.Builder confirm = new AlertDialog.Builder( this );
        confirm.setTitle("Credential Problem!");
        confirm.setMessage( "AWS Credentials not configured correctly.  Please review the README file." );
        confirm.setNegativeButton( "OK", new DialogInterface.OnClickListener() {
            public void onClick( DialogInterface dialog, int which ) {
                LogInPage.this.finish();
            }
        } );
        confirm.show().show();                
    } 
    
    public void verifyUser(String userName, String password){

    	
    	if(!SimpleDB.getDomainNames().contains(userName)  || 
    		!SimpleDB.getSingleAttributesForItem(userName, "passwordItem", "userPassword").equals(password)){
    		Message msg = myHandler.obtainMessage(VERIFY_FAILED) ;
    		
    		//FOR TESTING!!!!!! NEED TO BE CHANGED!!!!!!!!!!!!
    		if(userName.equals("")){
    			msg = myHandler.obtainMessage(VERIFY_TEST) ;
    		}
    		myHandler.sendMessage(msg);
    	}else{
    		Message msg = myHandler.obtainMessage(VERIFY_FINISHED) ;
    		myHandler.sendMessage(msg);
    	}	
    }
}
